package cc.customer.web.myCustomer;

import cc.customer.cAppNews.CAppNewsService;
import cc.customer.common.annotation.Log;
import cc.customer.common.domain.QueryRequest;
import cc.customer.common.domain.ResponseBo;
import cc.customer.common.utils.*;
import cc.customer.cusDynamic.domain.CusDynamic;
import cc.customer.cusDynamic.services.CusDynamicService;
import cc.customer.diaRecord.domain.CDydiaRecord;
import cc.customer.diaRecord.services.CdyDiaRecordServices;
import cc.customer.myCustomer.damain.CusResource;
import cc.customer.myCustomer.damain.EmpFenPei;
import cc.customer.myCustomer.damain.MyCustomer;
import cc.customer.myCustomer.damain.MyCustomerGroup;
import cc.customer.myCustomer.services.MyCustomerGroupService;
import cc.customer.myCustomer.services.MyCustomerService;
import cc.customer.rabbit.domain.CAppNews;
import cc.customer.rabbit.domain.CconvNotice;
import cc.customer.system.domain.MyUser;
import cc.customer.system.service.SaleTagService;
import cc.customer.system.service.UserService;
import cc.customer.web.sys.controller.base.BaseController;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping(value="myCustomer")
public class MyCustomerController extends BaseController {

private Logger logger = LoggerFactory.getLogger(MyCustomerController.class);

   @Autowired
   private MyCustomerGroupService mgService;

   @Autowired
   private MyCustomerService myCustomerService;

   @Autowired
   private CusDynamicService cusDynamicService;

   @Autowired
   private CdyDiaRecordServices cdyDiaRecordServices;

   @Autowired
   private CAppNewsService cAppNewsService;



   @Autowired
   private UserService userService;




   @RequestMapping(value="index")
   public String coustomerIndex(){
      return "customer/myCustomer/myCustomer_index";
   }

   @RequestMapping(value="loadCustomerGroup")
   public String loadCustomerGroup(){return "customer/myCustomer/myCustomer_group";}

   @RequestMapping(value="loadPhoneCall")
   public String loadPhoneCall(){return "customer/myCustomer/Phone_call";}

   @RequestMapping(value="loadCustomerDetail")
   public String loadCustomerDetail(String type){
      if (Constant.ZIYUAN_TYPE_EXEMP.equals(type)){
         //推广资源
         return "customer/myCustomer/myCustomerdetail/ext_detail";
      }else if (Constant.ZIYUAN_TYPE_SCHOLLE.equals(type)){
         return "customer/myCustomer/myCustomerdetail/onSchool_detail";
      }else if (Constant.ZIYUAN_TYPE_BIGENP.equals(type)){
         return "customer/myCustomer/myCustomerdetail/bigEmpDetail";
      }else if (Constant.ZIYUAN_TYPE_AI.equals(type)){
         return "customer/myCustomer/myCustomerdetail/aiEmpDetail";
      }
      return "customer/myCustomer/myCustomerdetail/myCustomer_detail";
   }

   /**共享关系**/
   @RequestMapping(value="/loadDistribute")
   public String loadDistribute(){return "customer/myCustomer/myCustomer_dustribute";}

   /**重新分配客户**/
   @RequestMapping(value="/loadAginDistribute")
   public String loadAginDistribute(){return "customer/myCustomer/myCustomer_aginDistrut";}

   /**给客户设置标签**/
   @RequestMapping(value="/loadCustomerLabel")
   public String loadCustomerLabel(){return "customer/myCustomer/myCustomer_setLabel";}
   /**转让客户**/
   @RequestMapping(value="/loadCustomertrancte")
   public String loadCustomertrancte(){return "customer/myCustomer/myCustomer_transfer";}
   /**加载添加销售计划界面*/
   @RequestMapping(value="/loadAddSalePlan")
   public String loadAddSalePlan(){return "customer/myCustomer/myCustomer_addplan";}
   /**加载我的客户重复*/
   @RequestMapping(value="/loadMyselfModal")
   public String loadMyselfModal(){return "customer/myCustomer/myCustomer_myself";}
   /**加载跟别人的客户重复*/
   @RequestMapping(value="/loadOtherModal")
   public String loadOtherModal(){return "customer/myCustomer/myCustomer_other";}
   /**加载客户查重*/
   @RequestMapping(value="/loadCkecking")
   public String loadCkecking(){return "customer/myCustomer/myCustomer_check";}
   /**加载重复客户的重复详情*/
   @RequestMapping(value="/loadCkeckDetail")
   public String loadCheckDetail(){return "customer/myCustomer/myCustomer_checkDetail";}


   /**添加分组**/
   @RequestMapping(value="addGroup")
   @ResponseBody
   public ResponseBo addCustomerGroup(MyCustomerGroup group){
      String userid = this.getCurrentUser().getUserUuid();
      group.setcGroupUserid(userid);
      return mgService.selectGroupName(group);
   }

   /**初始化分组列表**/
   @RequestMapping(value="selectGroupList")
   @ResponseBody
   public ResponseBo selectGroupList(){
      MyCustomerGroup group = new MyCustomerGroup();
      String userid = this.getCurrentUser().getUserUuid();
      group.setcGroupUserid(userid);
      List<MyCustomerGroup> list = mgService.selectAllGroup(group);
      return ResponseBo.ok("success",list);
   }
   /**初始化分组列表的树状图**/
   @RequestMapping(value="selectGroupListTree")
   @ResponseBody
   public ResponseBo selectGroupListTree(){
      String userid = this.getCurrentUser().getUserUuid();
      MyCustomerGroup group = new MyCustomerGroup();
      group.setcGroupUserid(userid);
      JSONArray list = mgService.selectAllGroupToArray(group);
      return ResponseBo.ok(list);
   }

   /**删除分组**/
   @RequestMapping(value="deleteGroup")
   @ResponseBody
   @Log("删除分组")
   public ResponseBo deleteGroup(MyCustomerGroup group){
      MyUser myUser= this.getCurrentUser();
      String userid =  myUser.getUserUuid();
      return mgService.deleteGroupName(group,userid);
   }
   /**分组排序**/
   @RequestMapping(value="sortGroup")
   @ResponseBody
   public ResponseBo sortGroup(MyCustomerGroup group){
      return mgService.sortGroup(group);
   }

   /**修改分组名称**/
   @RequestMapping(value="updateGroupName")
   @ResponseBody
   public ResponseBo updateGroupName(MyCustomerGroup group){
      return mgService.updateGroupName(group);
   }

   /**我的客户列表*/
   @RequestMapping(value = "/getMyCustomerList")
   @ResponseBody
   public Map<String,Object> getMyCustomerList(CusResource cusResource,QueryRequest request){
      MyUser user = this.getCurrentUser();
      String userid = user.getUserUuid();
      String deptid = user.getDeptId().toString();
      cusResource.setUserid(userid); cusResource.setDeptid(deptid);
      List<String> list = user.getAllAuthority();
      if (list.contains(Constant.AMDIN_AUTORITY)){
         cusResource.setIsHaveAdmin("yes");
      }
      return super.selectByPageNumSizeOrderBy(request, () -> this.myCustomerService.selectMyCustomer(cusResource,user));
   }

   /**放弃我的客户*/
   @RequestMapping(value="/giveUpMyCus")
   @ResponseBody
   @Log("放弃客户")
   public ResponseBo delMyCustomer(String keys,String types,String names){
      MyUser user = this.getCurrentUser();
      String userid = user.getUserUuid();
      ResponseBo responseBo = myCustomerService.giveUpMyCustomer(keys, types, userid, names);
      //客户uuid
     // List<String> uuidids = Arrays.asList(keys.split(","));
      //客户资源类型
      List<String> typeids = Arrays.asList(types.split(","));
      //客户id
      List<String> ids = Arrays.asList((keys+"").split(","));
      //客户名称
      List<String> name = Arrays.asList((names).split(","));

      CAppNews cAppNews = new CAppNews();
      CAppNews cAppNews1 = new CAppNews();
      if(0 == Integer.parseInt(responseBo.get("code").toString())){
         for(int t = 0;t < typeids.size();t++){

           //MyUser user1 = userService.findUserByUuids(cusResource.getReceiver());
            String  typeid = typeids.get(t);

            cAppNews.setcCousrsType(typeids.get(t));
            cAppNews.setCusid(ids.get(t));
            //cAppNews.setCustomerid(ids.get(t));
            cAppNews.setCustomername(name.get(t));
            cAppNews.setcConvNtype("1");
            cAppNews.setcConvType("1");
          //  cAppNews.setcSenderUser(user.getNickname());
            cAppNews.setcConvUsersName(user.getNickname());
             cAppNews.setcConvUsers(user.getUserUuid());
            cAppNews.setcConvTitle("放弃客户");
           // cAppNews.setcSenderUuid(user.getUserUuid());
            cAppNews.setcConvCont(user.getNickname()+"放弃的客户为："+name.get(t));
            cAppNewsService.addCAppNews(cAppNews);

         }
         return ResponseBo.ok();
      }else{
         return ResponseBo.error();
      }


   }

   /**分享我的客户*/
   @RequestMapping(value="/shareMyCustomer")
   @ResponseBody
   @Log("分享客户")
   public ResponseBo shareMyCustomer(CusResource cusResource,String flag,String names){
      MyUser user = this.getCurrentUser();
      String userid = this.getCurrentUser().getUserUuid();
      ResponseBo responseBo = myCustomerService.shareMyCustomer(cusResource, flag, userid, names);
      //客户uuid
      List<String> uuidids = Arrays.asList(cusResource.getUuid().split(","));
      //客户资源类型
      List<String> typeids = Arrays.asList(cusResource.getTypes().split(","));
      //客户id
      List<String> ids = Arrays.asList((cusResource.getIds()+"").split(","));
      //客户名称
      List<String> name = Arrays.asList((names).split(","));
      //分享用户
      List<String> sharcus = Arrays.asList((cusResource.getSharcus()).split(","));

      CAppNews cAppNews = new CAppNews();
      System.out.println( responseBo.get("code"));
      if(0 == Integer.parseInt(responseBo.get("code").toString())){
         for(int t = 0;t < typeids.size();t++){
            for(int i = 0;i < sharcus.size();i++) {
               MyUser user1 = userService.findUserByUuids(sharcus.get(i));
               String typeid = typeids.get(t);
               cAppNews.setcCousrsType(typeids.get(t));
               cAppNews.setCusid(ids.get(t));
               cAppNews.setCustomerid(uuidids.get(t));
               cAppNews.setCustomername(name.get(t));
               cAppNews.setcConvNtype("4");
               cAppNews.setcConvType("1");
               cAppNews.setcSenderUser(user.getNickname());
               cAppNews.setcConvUsersName(user1.getNickname());
               cAppNews.setcConvUsers(user1.getUserUuid());
               cAppNews.setcSenderUuid(user.getUserUuid());
               cAppNews.setcConvTitle("客户共享");
               cAppNews.setcConvCont("有同事给你共享了1个客户资源："+name.get(t) );
               cAppNewsService.addCAppNews(cAppNews);
            }
         }
         return ResponseBo.ok();
      }else {

      }  return ResponseBo.error();



   }

   /**转让客户**/
   @RequestMapping(value="/companyMyCustomerTransfer")
   @ResponseBody
   @Log("转让客户")
   public ResponseBo companyMyCustomerTransfer(CusResource cusResource,String names){
      MyUser user = this.getCurrentUser();
      String userid = user.getUserUuid();
      ResponseBo responseBo = myCustomerService.MyCustomerTransfer(cusResource, userid);
      //客户uuid
      List<String> uuidids = Arrays.asList(cusResource.getUuid().split(","));
      //客户资源类型
      List<String> typeids = Arrays.asList(cusResource.getTypes().split(","));
      //客户id
      List<String> ids = Arrays.asList((cusResource.getIds()+"").split(","));
      //客户名称
      List<String> name = Arrays.asList((names).split(","));
      //转让用户
      CAppNews cAppNews = new CAppNews();
      CAppNews cAppNews1 = new CAppNews();
      if(0 == Integer.parseInt(responseBo.get("code").toString())){
       /*  for(int t = 0;t < typeids.size();t++){
            MyUser user1 = userService.findUserByUuids(cusResource.getReceiver());
            String  typeid = typeids.get(t);

            cAppNews.setcCousrsType(typeids.get(t));
            cAppNews.setCusid(ids.get(t));
            cAppNews.setCustomerid(uuidids.get(t));
            cAppNews.setCustomername(name.get(t));
            cAppNews.setcConvNtype("2");
            cAppNews.setcConvType("1");
            cAppNews.setcSenderUser(user.getNickname());
            cAppNews.setcConvUsersName(user1.getNickname());
            cAppNews.setcConvUsers(user1.getUserUuid());
            cAppNews.setcConvTitle("客户转让");
            cAppNews.setcSenderUuid(user.getUserUuid());
            cAppNews.setcConvCont("有同事给转让了1个客户资源");
            cAppNewsService.addCAppNews(cAppNews);
         }*/
         return ResponseBo.ok();
      }else{
         return ResponseBo.error();
      }


   }

   /**批量设置客户得标签**/
   @RequestMapping(value="/setLabelMyCustomer")
   @ResponseBody
   @Log("批量设置标签")
   public ResponseBo setLabelMyCustomer(CusResource cusResource,String pid,String idstr,String uuid){
      String userid = this.getCurrentUser().getUserUuid();
      try {
         return myCustomerService.myCustomerLabel(cusResource,pid,idstr,userid);
      }catch (Exception e){
         e.printStackTrace();
      }
      return ResponseBo.error();
   }

   /**部门公海领取客户**/
   @RequestMapping(value="/reciverMyCustomer")
   @ResponseBody
   @Log("部门公海领取")
   public ResponseBo reciverMyCustomer(CusResource cusResource){
       MyUser user = this.getCurrentUser();
       String id = user.getUserUuid();
       cusResource.setReceiver(id);
       return myCustomerService.receviceMyCustomer(cusResource);
   }
   /**公司大公海客户的重新分配**/
   @RequestMapping(value="/companyMyCustomerDistore")
   @ResponseBody
   @Log("公司公海重新分配")
   public ResponseBo companyMyCustomerDistore(CusResource cusResource){
       String userid = this.getCurrentUser().getUserUuid();
       cusResource.setDistributor(userid);
       return myCustomerService.companyMyCustomerDistore(cusResource);
   }
   /**公司大公海客户的重新领取**/
   @RequestMapping(value="/companyMyCustomerLingqu")
   @ResponseBody
   @Log("公司公海重新领取")
   public ResponseBo companyMyCustomerLingqu(CusResource cusResource){
      String userid = this.getCurrentUser().getUserUuid();
      cusResource.setReceiver(userid);
      return myCustomerService.companyMyCustomerLingqu(cusResource);
   }

   /**导出excel**/
   @RequestMapping("/exportDetailforExcel")
   @ResponseBody
   public ResponseBo exportBigEmpDetailforExcel(String keyids){
      try {
         List<CusResource> list = myCustomerService.exportBigEmpInfo(keyids);
         ResponseBo responseBo = FileUtils.createExcelByPOIKit("客户资料表", list, CusResource.class);
         return responseBo;
      }catch (Exception e){
         logger.error("大资源名单导出大资源客户失败："+e.getMessage());
      }
      return ResponseBo.error("导出失败");
   }
   /**导出excel**/
   @RequestMapping("/exportDetailforFenPeiExcel")
   @ResponseBody
   public ResponseBo exportDetailforFenPeiExcel(String typeids,String keyids){
      try {
         List<EmpFenPei> list = myCustomerService.exportAllFenEmpInfo(typeids,keyids);
         ResponseBo responseBo = FileUtils.createExcelByPOIKit("客户资料表", list, EmpFenPei.class);
         return responseBo;
      }catch (Exception e){
         logger.error("分配资源名单导出大资源客户失败："+e.getMessage());
      }
      return ResponseBo.error("导出失败");
   }

   /**我的客户移动分组**/
   @RequestMapping("/moveCusGroup")
   @ResponseBody
   @Log("移动分组")
   public ResponseBo moveCusGroup(CusResource cusResource){
      return myCustomerService.moveCusGroup(cusResource);
   }

   /**我的客户添加跟进**/
   @RequestMapping("/addFollow")
   @ResponseBody
   @Log("添加跟进")
   public ResponseBo addFollow(CusDynamic dynamic){
      String userid = this.getCurrentUser().getUserUuid();
      return cusDynamicService.addFollow(dynamic,userid);
   }

   /**加载客户跟进详情**/
   @RequestMapping("/getDetailFollow")
   @ResponseBody
   public ResponseBo getDetailFollow(CusDynamic dynamic){
      String userid = this.getCurrentUser().getUserUuid();
      return cusDynamicService.getDetailFollow(dynamic,userid);
   }

   /**批量导入模板*/
   @RequestMapping("/downModal")
   @ResponseBody
   public ResponseBo downBigExcel(){
      try {
         MyCustomer excel = new MyCustomer();
         excel.setMyCusName("张三");
         excel.setMyCusSex("男");
         excel.setMyCusMobile("13370557555");
         excel.setMyCusQq("11211111");
         excel.setMyCusEmail("12345468@qq.com");
         excel.setMyCusWechat("asdsadsa");
         excel.setMyCusCity("济南地区");
         List<MyCustomer> list = new ArrayList<>();
         list.add(excel);
         return FileUtils.createExcelByPOIKit("我的客户批量导入表格模板", list, MyCustomer.class);
      } catch (Exception e) {
         return ResponseBo.error("导出Excel失败，请联系网站管理员！");
      }
   }

   /**上传录音文件**/
   @RequestMapping(value="/uploadRecordFile")
   @ResponseBody
   public ResponseBo uploadRecord(@RequestParam(name="file") MultipartFile[]file){
      logger.info("获取的文件："+file.length);
      if (file.length<=0){
         return ResponseBo.error("获取信息失败");
      }
      return FileUploadUtil.excuteFilesKeepName(file);
   }

   /**增加记录信息*
    * @param rname  录音的名称
    * @param uid    针对谁的录音
    * @param  phone 来电打进去的电话
    * @return
    */
   @RequestMapping(value="/uploadRecordSec")
   @ResponseBody
   public ResponseBo uploadRecord(String rname,String uid,String utype,String phone){
      MyUser user = this.getCurrentUser();
      JSONObject json = new JSONObject();
	   try {
          json = FileUploadUtil.getRecordDruidTime(rname);
	   }catch (Exception e){
		   logger.error("统计"+rname+"录音时长失败:"+e.getMessage());
	   }
      try {
         if (!StringUtils.isAnyEmpty(rname,uid,utype)){
            //判断是接听的  还是打出的
            if (rname.contains("Out")){
               //打出去
               List<String> list = new ArrayList<>();list.add(uid);
               CusDynamic cusde = new CusDynamic();
               cusde.setDyCreator(user.getUserUuid());
               cusde.setDySourceType(utype);
               cusde.setDyType(Constant.CUSTOMER_RECORD_DIAPHONE);
               cusde.setDyUrl(json.toJSONString());
               cusDynamicService.inserDynamic(list,cusde);
               return ResponseBo.ok();
            }
         }
         if (!StringUtils.isEmpty(phone)){
            //打进来的电话
            CDydiaRecord cDydiaRecord = new CDydiaRecord();
            cDydiaRecord.setsDiaNum(phone);
            cDydiaRecord.setsDiaUid(user.getUserUuid());
            cDydiaRecord.setsDiaUrl(json.toJSONString());
            cdyDiaRecordServices.addCdyDiaRecord(cDydiaRecord);
            return ResponseBo.ok();
         }
      }catch (Exception e){
         e.printStackTrace();
      }
      return ResponseBo.error();
   }

   /**客户查重*/
   @RequestMapping(value="checkCustomer")
   @ResponseBody
   public Map<String, Object> ckeckCustomer(QueryRequest request,CusResource cus){
      return super.selectByPageNumSize(request,() -> this.myCustomerService.checkCustomer(cus));
   }

   /**通过手机查询重复详情列表*/
   @RequestMapping(value="checkCusByMobile")
   @ResponseBody
   public Map<String,Object> checkCusByMobile(QueryRequest request,CusResource cus){
      return super.selectByPageNumSize(request,() -> this.myCustomerService.checkCustomerByMobile(cus));
   }


}
